package com.liam.chinesevietnamesecorpus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liam.chinesevietnamesecorpus.common.exception.ServiceException;
import com.liam.chinesevietnamesecorpus.dto.CorpusLibraryDTO;
import com.liam.chinesevietnamesecorpus.dto.CorpusLibraryUpdateDTO;
import com.liam.chinesevietnamesecorpus.entity.CorpusLibrary;
import com.liam.chinesevietnamesecorpus.mapper.CorpusLibraryMapper;
import com.liam.chinesevietnamesecorpus.service.CorpusLibraryService;
import com.liam.chinesevietnamesecorpus.vo.CorpusLibraryStatisticsVO;
import com.liam.chinesevietnamesecorpus.vo.CorpusLibraryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 语料库服务实现类
 * 
 * @author Liam
 */
@Slf4j
@Service
public class CorpusLibraryServiceImpl implements CorpusLibraryService {

    @Autowired
    private CorpusLibraryMapper corpusLibraryMapper;

    @Override
    @Transactional
    public CorpusLibraryVO createCorpusLibrary(CorpusLibraryDTO corpusLibraryDTO) {
        // 创建语料库对象
        CorpusLibrary corpusLibrary = BeanUtil.copyProperties(corpusLibraryDTO, CorpusLibrary.class);

        // 保存语料库
        int result = corpusLibraryMapper.insert(corpusLibrary);
        if (result <= 0) {
            throw new ServiceException("创建语料库失败");
        }

        log.info("语料库创建成功：{}", corpusLibrary.getName());

        // 转换为VO对象
        return BeanUtil.copyProperties(corpusLibrary, CorpusLibraryVO.class);
    }

    @Override
    public CorpusLibraryVO getCorpusLibraryById(Long id) {
        CorpusLibrary corpusLibrary = corpusLibraryMapper.selectById(id);
        if (corpusLibrary == null || "deleted".equals(corpusLibrary.getStatus())) {
            throw new ServiceException("语料库不存在");
        }
        return BeanUtil.copyProperties(corpusLibrary, CorpusLibraryVO.class);
    }

    @Override
    @Transactional
    public CorpusLibraryVO updateCorpusLibrary(Long id, CorpusLibraryUpdateDTO corpusLibraryUpdateDTO) {
        // 查询语料库是否存在
        CorpusLibrary existingLibrary = corpusLibraryMapper.selectById(id);
        if (existingLibrary == null || "deleted".equals(existingLibrary.getStatus())) {
            throw new ServiceException("语料库不存在");
        }

        // 更新语料库信息
        CorpusLibrary corpusLibrary = new CorpusLibrary();
        corpusLibrary.setId(id);
        BeanUtil.copyProperties(corpusLibraryUpdateDTO, corpusLibrary);

        int result = corpusLibraryMapper.updateById(corpusLibrary);
        if (result <= 0) {
            throw new ServiceException("更新失败");
        }

        log.info("语料库信息更新成功：{}", existingLibrary.getName());

        // 返回更新后的语料库信息
        return getCorpusLibraryById(id);
    }

    @Override
    @Transactional
    public void deleteCorpusLibrary(Long id) {
        // 查询语料库是否存在
        CorpusLibrary corpusLibrary = corpusLibraryMapper.selectById(id);
        if (corpusLibrary == null || "deleted".equals(corpusLibrary.getStatus())) {
            throw new ServiceException("语料库不存在");
        }

        // 软删除：更新状态为deleted
        CorpusLibrary deleteLibrary = new CorpusLibrary();
        deleteLibrary.setId(id);
        deleteLibrary.setStatus("deleted");

        int result = corpusLibraryMapper.updateById(deleteLibrary);
        if (result <= 0) {
            throw new ServiceException("删除失败");
        }

        log.info("语料库删除成功：{}", corpusLibrary.getName());
    }

    @Override
    public IPage<CorpusLibraryVO> getCorpusLibraryList(int page, int size, String keyword, String domain) {
        // 创建分页对象
        Page<CorpusLibrary> libraryPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<CorpusLibrary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(CorpusLibrary::getStatus, "deleted");
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like(CorpusLibrary::getName, keyword)
                .or()
                .like(CorpusLibrary::getDescription, keyword)
            );
        }
        
        if (StringUtils.hasText(domain)) {
            queryWrapper.eq(CorpusLibrary::getDomain, domain);
        }
        
        queryWrapper.orderByDesc(CorpusLibrary::getCreateTime);

        // 查询分页数据
        IPage<CorpusLibrary> libraryIPage = corpusLibraryMapper.selectPage(libraryPage, queryWrapper);

        // 转换为VO对象
        IPage<CorpusLibraryVO> libraryVOPage = new Page<>(libraryIPage.getCurrent(), libraryIPage.getSize(), libraryIPage.getTotal());
        libraryVOPage.setRecords(
            libraryIPage.getRecords().stream()
                .map(library -> BeanUtil.copyProperties(library, CorpusLibraryVO.class))
                .toList()
        );

        return libraryVOPage;
    }

    @Override
    public CorpusLibraryStatisticsVO getCorpusLibraryStatistics(Long id) {
        // 查询语料库是否存在
        CorpusLibrary corpusLibrary = corpusLibraryMapper.selectById(id);
        if (corpusLibrary == null || "deleted".equals(corpusLibrary.getStatus())) {
            throw new ServiceException("语料库不存在");
        }

        // 获取统计信息
        CorpusLibraryStatisticsVO statistics = corpusLibraryMapper.getLibraryStatistics(id);
        if (statistics == null) {
            throw new ServiceException("获取统计信息失败");
        }

        return statistics;
    }
}
